package cn.tedu.erp.project.config;

import cn.tedu.erp.project.filter.JwtAuthorizationFilter;
import cn.tedu.erp.project.web.JsonResult;
import cn.tedu.erp.project.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限验证,在方法之前
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//创建一个密文密码编码器
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();//身份验证
    }

    //注入过滤器对象
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    //重写WebSecurityConfigurerAdapter的方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //处理未通过认证时导致的拒绝访问
        http.exceptionHandling().authenticationEntryPoint(
                new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         AuthenticationException e)
                            throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter writer = httpServletResponse.getWriter();
                        JsonResult<Void> jsonResult =
                                JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED, "您当前未登录,请登录!");
                        String jsonString = JSON.toJSONString(jsonResult);
                        writer.println(jsonString);
                        writer.close();
                    }
                });
        //禁用"防止伪造跨域攻击"的防御机制
        http.csrf().disable();
        //防止复杂请求的跨域
        http.cors();
        //白名单
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/admins/login"
        };
        //请求路径的访问控制
        http.authorizeRequests()//对请求进行授权
                .mvcMatchers(HttpMethod.OPTIONS,"/**")
                .permitAll()//对浏览器的复杂请求进行放行(解决复杂请求的跨域问题)
                .mvcMatchers(urls)//匹配某些请求
                .permitAll()//直接许可,不需要认证即可访问
                .anyRequest()//任意请求
                .authenticated();//要求通过认证的
        http.addFilterBefore(jwtAuthorizationFilter,
                UsernamePasswordAuthenticationFilter.class);
        //配置spring security创建session的策略,从不使用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
